import { ref, onMounted, onUnmounted } from 'vue'

export default function useDateTime(format = 'YYYY年MM月DD日 HH:mm:ss WW') {
  const dateTime = ref('')
  const weekDays = [
    '星期日',
    '星期一',
    '星期二',
    '星期三',
    '星期四',
    '星期五',
    '星期六',
  ]
  let timer = null

  // 更新时间的函数
  const updateTime = () => {
    const now = new Date()
    const year = String(now.getFullYear())
    const month = (now.getMonth() + 1).toString().padStart(2, '0')
    const day = now.getDate().toString().padStart(2, '0')
    const hour = now.getHours().toString().padStart(2, '0')
    const minute = now.getMinutes().toString().padStart(2, '0')
    const second = now.getSeconds().toString().padStart(2, '0')
    const week = weekDays[now.getDay()]

    dateTime.value = format
      .replace('YYYY', year)
      .replace('MM', month)
      .replace('DD', day)
      .replace('HH', hour)
      .replace('mm', minute)
      .replace('ss', second)
      .replace('WW', ` | ${week}`)
  }

  // 组件挂载时启动定时器
  onMounted(() => {
    updateTime() // 立即更新一次
    timer = setInterval(updateTime, 1000) // 每秒更新一次
  })

  // 组件卸载时清除定时器
  onUnmounted(() => {
    if (timer) clearInterval(timer)
  })

  return {
    dateTime,
  }
}
